package main

import (
	"bufio"
	"fmt"
	"net"
	"os"
)

// 客户端
func main() {
	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s host:port", os.Args[0])
		os.Exit(1)
	}
	service := os.Args[1]
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
	checkErr(err)
	conn, err := net.DialTCP("tcp4", nil, tcpAddr)
	checkErr(err)
	_, err = conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))
	checkErr(err)
	result := make([]byte, 256)
	_, err = conn.Read(result)
	checkErr(err)
	fmt.Println(string(result))
	inputReader := bufio.NewReader(os.Stdin)
	for {
		fmt.Print("input the data to server(q for quit):")
		var input string
		//fmt.Scanln(&input)
		input, _ = inputReader.ReadString('\n')
		if input == "q" || input == "quit" {
			break
		}
		_, err = conn.Write([]byte(input))
		checkErr(err)
		_, err = conn.Read(result)
		checkErr(err)
		fmt.Println(string(result))
	}

	os.Exit(0)
}

func checkErr(err error) {
	if err != nil {
		fmt.Fprint(os.Stderr, "Fatal error: %s", err.Error())
		os.Exit(1)
	}
}
